#ifndef LISTED_TIMER_H
#define LISTED_TIMER_H


#include <ctime>
#include <cerrno>
#include <cassert>

#include <functional>
#include <unordered_map>
#include <utility>

#include "../lock/locker.h"

namespace ListedTimer {
    typedef std::function<void()> TimerTask;

    struct TimerNode {
        int id;
        TimerNode *prev, *next;      // 双向链表节点
        time_t expiry_time;          // 超时时间点
        TimerTask task;              // 超时任务
        TimerNode(int t_id, time_t t_expiry, TimerTask t_task) :
            id(t_id), expiry_time(t_expiry), task(std::move(t_task)) {
            prev = next = nullptr;
        }
        TimerNode(): id(-1), expiry_time(0), prev(nullptr), next(nullptr), task(nullptr){}
    };


    class SortedTimers {
    public:
        SortedTimers();
        ~SortedTimers();
        void add(int id, int timeout_s, const TimerTask &task);
        void adjust(int id, uint32_t timeout);
        void erase(int id);
        void tick();
        int get_next_tick();

    private:
        void insert(TimerNode*timer, TimerNode *begin_node);

    private:
        unsigned int max_nodes;
        TimerNode *head = nullptr;
        TimerNode *tail = nullptr;   // 双向链表
        TimerNode **m_nodes_table;
//        std::unordered_map<int, TimerNode*> m_nodes_table;
        Locker m_lock;
    };
}




#endif //LISTED_TIMER_H
